#include <tinx/device.h>
#include <tinx/task.h>
#include <tinx/buffer.h>
#include <tinx/interrupt.h>
#include <tinx/syscall.h>
#include <tinx/printf.h>

void broke_stack(int count)
{
    if (!count)
        return;
    broke_stack(--count);
}

extern int main();

void init_user_mode()
{
    // test();

    while (1)
    {
        pid_t pid = fork();
        u32 status;
        if (pid)
        {
            waitpid(pid, &status, 0);
            printf("task pid %d exits status %d\n", pid, status);
        }
        else
        {
            main();
            exit(0);
        }
    }
}

static void prepare_stack()
{
    asm volatile(
        "subl $100, %%esp\n"
        "pushl %%eax\n"
        "ret\n" :: "a"(__builtin_return_address(0))
    );
}

extern void keyboard_init();
extern void part_init();
extern void ide_init();
extern void ramdisk_init();
extern void swap_init();

extern void vm86_init();
extern void fb_init();

extern void buffer_init();
extern void fs_init();

void init_thread()
{
    keyboard_init();
    part_init();
    ide_init();
    ramdisk_init();
    buffer_init();
    fs_init();
    swap_init();

    // vm86_init();
    // fb_init();

    prepare_stack();
    task_to_user_mode(init_user_mode);
}